﻿using CinemaMaestro.BusinessLayer.Contracts;
using CinemaMaestro.DataLayer.Contracts;
using CinemaMaestro.DataLayer.Contracts.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CinemaMaestro.BusinessLayer
{
    public class Reservations : BusinessObjectBase, IReservations
    {
        public Reservations(IUnitOfWork uow)
            : base(uow)
        { }

        public bool Create(Reservation reservation)
        {
            using (var transaction = _uow.BeginTransaction())
            {
                var roomCapacity = reservation.Screening.Room.Capacity;

                var reservedSeatCount = _uow.ReservationRepository.Read()
                    .Where(x => x.Screening.Id == reservation.Screening.Id)
                    .Sum(x => x.TicketNr + x.DiscountTicketNr);

                var soldSeatCount = _uow.SaleRepository.Read()
                    .Where(x => x.Screening.Id == reservation.Screening.Id)
                    .Sum(x => x.TicketNr + x.DiscountTicketNr);

                var availableSeatCount = roomCapacity - soldSeatCount - reservedSeatCount;

                if (availableSeatCount >= (reservation.TicketNr + reservation.DiscountTicketNr))
                {
                    var createdSale = _uow.ReservationRepository.Create(reservation);
                    
                    _uow.SaveChanges();
                    transaction.Commit();
                    return true;
                }
                return false;
            }
        }

        public bool Delete(int id)
        {
            var deleted = _uow.ReservationRepository.Delete(id);
            _uow.SaveChanges();
            return deleted;
        }

        public IQueryable<Reservation> Read()
        {
            return _uow.ReservationRepository.Read();
        }

        public void Update(Reservation entity)
        {
            _uow.ReservationRepository.Update(entity);
            _uow.SaveChanges();
        }

        public bool ReservationHasRelationWithScreening(int screeningId)
        {
            bool hasRelation = Read().Any(x => x.Screening.Id == screeningId);
            return hasRelation;
        }
    }
}
